package zheezes.mail;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.InitialDirContext;

import zheezes.util.ZRegex;

public class ZDns {
	private static Random rand = new Random(System.currentTimeMillis());

	private static String pubIp = null;

	@SuppressWarnings("rawtypes")
	public static String[] getAllAttr(String host, String name, int num) {
		if (host == null) {
			return null;
		}
		
		List<String> list = null;
		try {
			InitialDirContext context = new InitialDirContext();
			Attributes attrs = context.getAttributes("dns:/" + host);
			NamingEnumeration enums = attrs.getAll();
			list = new ArrayList<String>();
			String key, value;
			int colon;
			while (enums.hasMore()) {
				if (num >= 0 && list.size() >= num) {
					break;
				}
				String attr = enums.next().toString();
				if (name == null) {
					list.add(attr);
				} else {
					colon = attr.indexOf(':');
					key = attr.substring(0, colon).trim();
					if (name.compareToIgnoreCase(key) != 0) {
						continue;
					}
					value = attr.substring(colon + 1);
					list.add(value);
				}
			}
		} catch (NamingException e) {
		}

		if (list == null) {
			return null;
		}

		return list.toArray(new String[0]);
	}

	public static String getOneAttr(String host, String name, int index) {
		if (index < 0) {
			return null;
		}
		String[] attrs = ZDns.getAllAttr(host, name, 1);
		if (attrs == null || attrs.length <= index) {
			return null;
		}
		return attrs[index];
	}

	public static String[] getAllMX(String host) {
		String attr = ZDns.getOneAttr(host, "MX", 0);
		if (attr == null) {
			return null;
		}
		String[] mxs = attr.split(",");
		return mxs;
	}

	public static String getOneMx(String host, int index) {
		String[] mxs = getAllMX(host);
		if (mxs == null || mxs.length == 0) {
			return null;
		}
		if (index < 0) {
			index = rand.nextInt(mxs.length);
		}
		return mxs[index];
	}

	public static String getOneMxHost(String host, int index) {
		String mx = getOneMx(host, index);
		if (mx == null) {
			return null;
		}
		String[] dots = mx.split(" ");
		for (String s : dots) {
			if (!s.endsWith(".")) {
				continue;
			}
			return s.substring(0, s.length() - 1);
		}
		return null;
	}

	public static String getTopDomain(String domain) {
		if (domain == null) {
			return null;
		}
		char[] cs = { '@', '#' };
		for (char c : cs) {
			int index = domain.lastIndexOf(c);
			if (index < 0) {
				continue;
			}
			domain = domain.substring(index + 1);
		}
		String[] dots = domain.split("\\.");
		int num = dots.length;
		if (num < 2) {
			return null;
		}
		return String.format("%s.%s", dots[num - 2], dots[num - 1]);
	}

	public static String getPubIp(boolean cache) {
		if (pubIp != null && cache) {
			return pubIp;
		}

		Set<String> set = new HashSet<String>();
		Pattern pattern = ZRegex.pattern(ZRegex.PATTERN_IPADDR);

		try {
			URL url = new URL("http://ip.qq.com");
			InputStream is = url.openConnection().getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			String line = null;
			while ((line = br.readLine()) != null) {
				Matcher matcher = pattern.matcher(line);
				while (matcher.find()) {
					set.add(matcher.group());
					continue;
				}
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		if (set.size() == 0) {
			return null;
		}

		pubIp = set.toArray(new String[0])[0];

		return pubIp;
	}
}
